<template>
  <div class="container">
    <br />
    <el-form :inline="true" class="demo-form-inline" label-width="88px">
      <el-form-item label="挂号单ID:">
        <el-input v-model="query.idCard" placeholder="请输入挂号单ID" size="small" id="id" style="width:300px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" size="small" @click="getLists">读取IC卡</el-button>
      </el-form-item>
    </el-form>
    <div v-if=careHistory2>
      <el-card style="margin-bottom: 5px">
        <el-form label-position="right" label-width="120px" inline class="demo-table-expand">
          <el-row>
            <el-col :span="12">
              <el-form-item label="挂号单号:">
                <span style="color: red;" v-text="careHistory.regId" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="医生姓名:">
                <span style="color: red;" v-text="careHistory.userName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="科室名称:">
                <span style="color: red;" v-text="careHistory.deptName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="患者姓名:">
                <span style="color: red;" v-text="careHistory.patientName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="就诊时间:">
                <span style="color: red;" v-text="careHistory.careDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主诉:">
                <span style="color: red;" v-text="careHistory.caseTitle" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="诊断信息:">
                <span style="color: red;" v-text="careHistory.caseResult" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="医生建议:">
                <span style="color: red;" v-text="careHistory.doctorTips" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card style="margin-bottom: 5px">
        <el-button type="success" icon="finished" @click="selectAll">全选</el-button>
        <el-button style="background-color: gray;" @click="handleUnSelectAll" type="success"
          icon="finished">取消全选</el-button>
        <el-button type="danger" icon="money" @click="handlePayWithCash">确认发货</el-button>
        <span style="margin-left: 20px">订单总额: <span style="color: red;">￥{{ allAmount }}</span></span>
      </el-card>
      <el-card>
        <div class="button-with-icon" v-if=pd>
          <button @click="toggleOpen" style="background-color: white;">
            【<span style="color: red;">药用处方</span>】 【处方总和】: <span style="color: red;">￥{{ totalRs }}</span>
            <el-icon class="icon-right">
              <ArrowDown />
            </el-icon>
          </button>
        </div>

        <transition name="fade">
          <div v-if="isOpen" class="content">
            <el-table :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
              :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="40" />
              <el-table-column prop="itemId" label="序号" width="100" v-if="false" />
              <el-table-column label="序号" width="100">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="itemName" label="药品名称" width="180" />
              <el-table-column prop="num" label="数量" width="180" />
              <el-table-column prop="price" label="单价(元)" width="180" />
              <el-table-column prop="amount" label="金额(元)" width="180" />
              <el-table-column prop="remark" label="备注" width="180" />
              <el-table-column label="状态" align="center" prop="status">
                <template v-slot:default="{ row }">
                  <el-tag>已支付</el-tag>
                </template>
              </el-table-column>

            </el-table>
          </div>
        </transition>
        <div class="button-with-icon" v-if=pd2>
          <button @click="toggleOpen01" style="background-color: white;">
            【<span style="color: red;">检查处方</span>】 【处方总和】: <span style="color: red">￥{{ totalRs01 }}</span>
            <el-icon class="icon-right">
              <ArrowDown />
            </el-icon>
          </button>
        </div>
        <transition name="fade">
          <div v-if="isOpen01" class="content">
            <el-table :data="tableData01" @selection-change="handleSelectionChange01"
              :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
              <el-table-column type="selection" width="40" />
              <el-table-column prop="itemId" label="序号" width="100" v-if="false" />
              <el-table-column label="序号" width="100">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="itemName" label="项目名称" width="180" />
              <el-table-column prop="num" label="数量" width="180" />
              <el-table-column prop="price" label="单价(元)" width="180" />
              <el-table-column prop="amount" label="金额(元)" width="180" />
              <el-table-column prop="remark" label="备注" width="180" />
              <el-table-column label="状态" align="center" prop="status">
                <template v-slot:default="{ row }">
                  <el-tag>已支付</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </transition>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import service from '@/utils/request';
import { ArrowDown, Search } from '@element-plus/icons-vue';
import { ca } from 'element-plus/es/locale';


const isOpen = ref(false);
const isOpen01 = ref(false);

const pd = ref(false);
const pd2 = ref(false);
const careHistory2 = ref(false);


const tableData = ref([]);
const tableData01 = ref([]);


const totalRs = ref(0); // 添加一个响应式变量来存储总和
const totalRs01 = ref(0); // 添加一个响应式变量来存储总和

const allAmount = ref(0); // 添加一个响应式变量来存储订单总额

// 方法用来计算rs列的总和
const calculateTotalRs = () => {
  let sum = 0;

  tableData.value.forEach(row => {
    sum += (row.amount * row.num);
  });

  totalRs.value = sum;
};
const calculateTotalRs01 = () => {
  let sum = 0;
  tableData01.value.forEach(row => {
    sum += (row.amount * row.num); // 假设总金额是在totalAmount字段
  });
  totalRs01.value = sum;
};
// 监听tableData的变化
watchEffect(() => {
  calculateTotalRs();
  calculateTotalRs01();
});

const toggleOpen = () => {
  isOpen.value = !isOpen.value;
  calculateTotalRs(); // 展开或收起表格时重新计算总和
};
const toggleOpen01 = () => {
  isOpen01.value = !isOpen01.value;
  calculateTotalRs01(); // 展开或收起表格时重新计算总和
};


const careHistory = reactive({
  chId: '',
  regId: '',
  userName: '',
  deptName: '',
  patientName: '',
  careDate: '',
  caseTitle: '',
  caseResult: '',
  doctorTips: '',

});

const query = reactive({
  idCard: ''
});
// 点击“读取IC卡”时执行的方法
const getLists = async () => {
  console.log('挂号单ID:', query.idCard);
  if (query.idCard === '') {
    ElMessage.error('请输入挂号单ID');
    return;
  } else {
    const res = await service.post('/api/v1/jdbc/hisOrderCharge/selectAll1', query.idCard);
    if (res === null) {
      ElMessage.error('未找到挂号单');
      location.reload();
      return;
    } else {
      console.log(res);
      careHistory2.value = true;
      const rid = res.chId;
      if (rid != null) {
        const res2 = await service.post('/api/v1/jdbc/hisOrderCharge/selectChargeDetail', rid);
        console.log(res2);
        const coid = res2[0].patientId;
        console.log(coid);

        if (coid != null) {
          const res3 = await service.post('/api/v1/jdbc/hisOrderCharge/selectChargeDetail8', coid);
          const res4 = await service.post('/api/v1/jdbc/hisOrderCharge/selectChargeDetail9', coid);
          if (res3 != null && res3.length > 0) {
            console.log(res3);
            tableData.value = res3;
            pd.value = true;
          }
          if (res4 != null && res4.length > 0) {
            console.log(res4);
            tableData01.value = res4;
            pd2.value = true;

          }
        }
        careHistory.regId = res.regId;
        careHistory.userName = res.userName;
        careHistory.deptName = res.deptName;
        careHistory.patientName = res.patientName;
        careHistory.careDate = res.caseDate;
        careHistory.caseTitle = res.caseTitle;
        careHistory.caseResult = res.caseResult;
        careHistory.doctorTips = res.doctorTips;
        careHistory.chId = res.chId;
      }
    }
  }
};


const isAllSelected = ref(false);
const allit = ref([]);
const handleSelectionChange = (selection: any[]) => {
  isAllSelected.value = selection.length === tableData.value.length + tableData01.value.length;
  updateAllAmount(selection);
};

const handleSelectionChange01 = (selection: any[]) => {
  isAllSelected.value = selection.length === tableData01.value.length + tableData.value.length;
  updateAllAmount(selection);
};


const selectAll = () => {
  const newSelection = isAllSelected.value ? [] : [...tableData.value, ...tableData01.value];
  isAllSelected.value = !isAllSelected.value;
  updateAllAmount(newSelection);

};

const handleUnSelectAll = () => {
  isAllSelected.value = false;
  updateAllAmount([]);
};

const handlePayWithCash = async () => {
  console.log(allit.value);
  const y = ref(false)
  if (allit.value != null) {
    for (let i = 0; i < allit.value.length; i++) {
      const res = await service.post('/api/v1/jdbc/hisOrderCharge/updateChargeDetail3', allit.value[i]);
      y.value = true;
    }
    if (y) {
      ElNotification.success({
        title: '成功',
        message: "发货成功",
      })
      location.reload();
    } else {
      ElMessage.error('发货失败');
    }
  }

}


const updateAllAmount = (selection: any[]) => {
  let amount = 0;
  let itemIds = []; // 创建一个新的数组来存储所有的 itemId
  console.log(selection);

  selection.forEach(item => {
    amount += item.amount * item.num;
    itemIds.push(item.itemId); // 将每个 itemId 添加到 itemIds 数组中


  });

  allAmount.value = amount;
  allit.value = itemIds; // 将整个数组赋值给 allit.value
};


</script>

<style scoped>
.container {
  margin-left: 20px;
  /* 调整这个值以改变左边距 */
}

.demo-table-expand .el-form-item__label {
  text-align: right;
  padding-right: 10px;
}

.demo-table-expand .el-form-item {
  margin-right: 20px;
}

.button-with-icon {
  position: relative;
  background-color: white;
}

.icon-right {
  position: absolute;
  right: 10px;
  /* 调整与右侧边距 */
  top: 50%;
  transform: translateY(-50%);
}
</style>
